using Microsoft.AspNetCore.Mvc;
using ElectronicMallProject.Backend.Api.Repository;
using ElectronicMallProject.Backend.Api.Entity;
using System.Linq;
using Microsoft.Extensions.Configuration;
using ElectronicMallProject.Backend.Api.Params;
using ElectronicMallProject.Backend.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using System.Collections;

namespace ElectronicMallProject.Backend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {

        private IRepository<Users> _usersRepository;
        private IConfiguration _configuration;
        private readonly IRepository<Sales> _salesRepository;
        private readonly IRepository<Commodity> _commodityRepository;
        private TokenParameter _tokenparameter;
        public UsersController(IRepository<Users> usersRepository, IConfiguration configuration, IRepository<Sales> salesRepository, IRepository<Commodity> commodityRepository)
        {
            _usersRepository = usersRepository;

            _configuration = configuration;

            _salesRepository = salesRepository;

            _commodityRepository = commodityRepository;

            _tokenparameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        //获取所有用户
        [HttpGet, Route("get")]
        public dynamic Get()
        {
            var Users = _usersRepository.Table;
            return new
            {
                Code = 200,
                Data = Users,
                Msg = "获取用户成功"
            };
        }

        // [HttpGet("{id}")]
        // public dynamic getById(int id)
        // {
        //     var ss = _salesRepository.Table.Where(x => x.CommodityId == id).ToList();

        //     var uu = _salesRepository.Table.Where(x => x.UserId == id).ToList();

        //     ArrayList list = new ArrayList();


        // }

        //获取管理员用户
        [HttpGet, Route("getadmin")]
        public dynamic AdminGet()
        {
            var user = _usersRepository.Table;
            var userrole = user.Where(x => x.UserRole.Equals("管理员")).FirstOrDefault();

            if (userrole == null)
            {
                var res = new
                {
                    Code = 104,
                    Data = "",
                    Msg = "没有找到管理员"
                };
                return JsonHelper.Serialize(res);
            }
            else
            {
                return new
                {
                    Code = 200,
                    Data = userrole,
                    Msg = "获取管理员成功"
                };

            }

        }

        //获取商家用户
        [HttpGet, Route("getbusiness")]
        public dynamic BusinessGet()
        {
            var user = _usersRepository.Table;
            var userrole = user.Where(x => x.UserRole.Equals("商家")).FirstOrDefault();

            if (userrole == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "没有找到商家"
                };
            }
            else
            {
                return new
                {
                    Code = 200,
                    Data = userrole,
                    Msg = "获取商家成功"
                };

            }
        }

        //获取用户
        [HttpGet, Route("getusers")]
        public dynamic UsersGet()
        {
            var user = _usersRepository.Table;
            var userrole = user.Where(x => x.UserRole.Equals("用户"));

            if (userrole == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "没有找到用户"
                };
            }
            else
            {
                return new
                {
                    Code = 200,
                    Data = userrole,
                    Msg = "获取用户成功"
                };

            }
        }

        //用户登录
        [HttpPost, Route("userslogin")]
        public dynamic Post(LoginUsers loginusers)
        {
            var username = loginusers.UserName.Trim();
            var password = loginusers.PassWord.Trim();
            var user = _usersRepository.Table.Where(x => x.UserName == username && x.PassWord == password).FirstOrDefault();

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                if (user == null)
                {
                    return new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "用户名或密码错误"
                    };
                }

                var token = TokenHelper.GenUserToken(_tokenparameter, user.UserName);
                var refreshToken = "123456789";

                if (user.IsActived == false)
                {
                    return new
                    {
                        Code = 105,
                        Data = "",
                        Msg = "该用户已被封号"
                    };
                }
                else
                {
                    if (user.UserRole == "用户")
                    {
                        return new
                        {
                            Code = 200,
                            Data = new { Token = token, refreshToken = refreshToken, user = user },
                            Msg = "用户登陆成功"
                        };
                    }
                    else if (user.UserRole == "商家")
                    {
                        return new
                        {
                            Code = 200,
                            Data = new { Token = token, refreshToken = refreshToken, user = user },
                            Msg = "商家登陆成功"
                        };
                    }
                    return new
                    {
                        Code = 200,
                        Data = new { Token = token, refreshToken = refreshToken, user = user },
                        Msg = "管理员登陆成功"
                    };
                }
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名密码不能为空"
                };
            }
        }

        //用户注册
        [HttpPost, Route("userregistry")]
        public dynamic Post(CreateUsers newUser)
        {
            var username = newUser.UserName.Trim();
            var password = newUser.PassWord.Trim();
            var repassword = newUser.RePassword.Trim();
            var userrole = newUser.UserRole.Trim();

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(repassword) && !string.IsNullOrEmpty(userrole))
            {
                if (!password.Equals(repassword))
                {
                    return new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "两次密码输入不一致"
                    };
                }
                var user = _usersRepository.Table;
                var ishaveuser = user.Where(x => x.UserName.Equals(username)).ToList();

                //注册用户
                if (ishaveuser.Count() == 0)
                {
                    var res = new Users
                    {
                        UserName = username,
                        PassWord = password,
                        UserRole = userrole
                    };

                    _usersRepository.Insert(res);

                    return new
                    {
                        Code = 200,
                        Data = res,
                        Msg = "注册用户成功"
                    };
                }
                else
                {
                    return new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "该用户已注册"
                    };
                }
            }
            else
            {
                //用户名密码不能为空
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名密码不能为空"
                };
            }
        }

        //修改用户密码
        [HttpPut, Route("{id}/changeusers")]
        public dynamic Put(int id, ChangeUsers changeusers)
        {
            var username = changeusers.UserName.Trim();
            var password = changeusers.PassWord.Trim();

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var user = _usersRepository.GetById(id);
                if (user == null)
                {
                    return new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "要修改的用户不存在"
                    };
                }
                user.UserName = changeusers.UserName;
                user.PassWord = changeusers.PassWord;

                _usersRepository.Updated(user);

                return new

                {
                    Code = 200,
                    Data = user,
                    Msg = "修改用户成功"
                };
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名密码不能为空"
                };
            }
        }


        [HttpPut("{id}/changeusercustomerorderaddress")]
        //修改用户地址
        public dynamic ChangeUserCustomerOrderAddress(int id,ChangeUserCustomerOrderAddress changeUserCustomerOrderAddress)
        {
            var customerOrderAddress = changeUserCustomerOrderAddress.CustomerOrderAddress.Trim();
                var user = _usersRepository.GetById(id);

                if(user == null)
                {
                    return new 
                    {
                        code = 104,
                        data = "",
                        msg = "找不到该用户"
                    };
                }

                user.CustomerOrderAddress = customerOrderAddress.Trim();
                _usersRepository.Updated(user);

                return new
                {
                    code = 200,
                    data = user,
                    msg = "修改成功"
                };
        }

        //分配用户角色
        [HttpPut, Route("{id}/distributionrole")]
        public dynamic distributionPut(int id, CreateUserRole create)
        {
            var userrole = create.UserRole.Trim();

            if (!string.IsNullOrEmpty(userrole))
            {
                var user = _usersRepository.GetById(id);

                if (user == null)
                {
                    return new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "要分配角色的用户不存在"
                    };
                }

                user.UserRole = create.UserRole;

                _usersRepository.Updated(user);

                return new
                {
                    Code = 200,
                    Data = user,
                    Msg = "分配用户角色成功"
                };
            }
            return "";
        }

        //冻结用户
        [HttpPut, Route("{id}/frozenusers")]
        public dynamic frozenPut(int id)
        {
            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该用户不存在"
                };
            }
            user.IsActived = false;
            _usersRepository.Updated(user);

            return new
            {
                Code = 200,
                Data = user,
                Msg = "冻结用户成功"
            };
        }


        //启用用户
        [HttpPut, Route("{id}/enableusers")]
        public dynamic enablePut(int id)
        {
            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该用户不存在"
                };
            }
            user.IsActived = true;
            _usersRepository.Updated(user);

            return new
            {
                Code = 200,
                Data = user,
                Msg = "启用用户成功"
            };
        }

        //刷新重新获取token
        [AllowAnonymous]
        [HttpPost, Route("userRefreshToken")]
        public dynamic UserRefreshTokenPost(RefreshTokenDTO refresh)
        {
            var users = _usersRepository.Table;
            var user = TokenHelper.ValidateToken(_tokenparameter, refresh);

            if (string.IsNullOrEmpty(user))
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "userRefreshToken验证失败"
                };
            }

            var token = TokenHelper.GenUserToken(_tokenparameter, user);

            var refreshToken = "123456789";

            return new
            {
                Code = 200,
                Data = new { token = token, refreshToken = refreshToken, users = users },
                Msg = "刷新重新获取token,refreshToken成功"
            };
        }


        //查询用户
        [HttpPost,Route("userQuery")]
        public dynamic UserQuery(Myquery querydata){
            var query = querydata.queryData.Trim();
            var users = _usersRepository.Table.ToList(); 
            var queryUsers = users.Where(x =>x.UserName.Contains(query)
             || x.UserRole.Contains(query)).ToList();
            return new {
                code = 200,
                data = queryUsers,
                msg = "查询用户成功"
            };
        }

    }
}